<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm w100">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item class="btm10">
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      // 对用户名和密码进行校验
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '3到16位（字母，数字，下划线，减号）', trigger: 'red' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 16, message: '3到16位（字母，数字，下划线，减号）', trigger: 'red' },
        ],
      },
    }
  },
  methods: {
    // 登录并向服务器请求
    submitForm(formName) {
      console.log(formName)
      this.$refs[formName].validate(async (flag) => {
        if (!flag) return this.$message.error('用户名或密码错误')
        const { data } = await this.$http.post('login', this.ruleForm)
        // 1.将token存储到sessionStroage中  除了login请求其他的都要携带token
        if (data.meta.status !== 200) return this.$message.err('密码错误')
        sessionStorage.setItem('token', data.data.token)
        // 2.弹窗提示登录成功
        this.$message({
          message: '登录成功',
          type: 'success',
        })
        // 3.跳转到/home
        this.$router.push('/home')
      })
    },
    // 重置输入框
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
  mounted() {
    // console.log(this.ruleForm.username)
  },
}
</script>
<style lang="less">
.w100 {
  width: 400px;
}
.el-form-item__content:last-child {
  margin-top: 10px;
}
</style>
